import React, { useContext, useEffect, useState } from 'react';
import cs from 'classnames';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import styles from './style/index.module.less';
import {
  Button,
  Input,
  Message,
  Skeleton,
  Space,
  Spin,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import {
  IconCheck,
  IconClose,
  IconDelete,
  IconEdit,
  IconFile,
  IconToBottom,
  IconUpload,
} from '@arco-design/web-react/icon';
import { ViolationDetails } from '@/api/interface/violation';
import ActionWrapper from '@/components/ActionWrapper';
import AppUpload from '@/components/AppUpload';
import { usedownloadDoc } from '@/utils/useDownload';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import { updateAttachment } from '@/api/modules/violation';

function Attachments({
  details,
  loading,
  onFile,
  setViolationDetails,
}: {
  details: ViolationDetails;
  loading: boolean;
  onFile: (file: Array<any>) => void;
  setViolationDetails: (details: any) => void;
}) {
  const { rtl } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [fileList, setfFleList] = useState([]);

  const actions = useSelector((state: GlobalState) => state.actions);

  const onAdd = (e) => {
    const files = e.map((a) => ({ desc: '', href: a.href, isDel: true }));
    setfFleList((a) => [...a, ...files]);
  };

  useEffect(() => {
    onFile(fileList);
  }, [fileList]);

  const onRemove = (href) => {
    const arr = fileList.filter((a) => a.href !== href);
    setfFleList(arr);
  };

  const onStart = (row) => {
    const arr = [...details.supportEntities];
    const index = arr.findIndex((a) => a.id === row.id);

    arr[index].edit = true;
    arr[index].cacheFileName = arr[index].fileName;
    setViolationDetails((a) => ({ ...a, supportEntities: arr }));
  };

  function getFileExtension(filename) {
    return filename.substring(filename.lastIndexOf('.') + 1);
  }

  const onEnd = (row) => {
    if (!row.fileName) {
      onCancel(row);
      return;
    }
    const name = getFileExtension(row.href);
    const params = {
      fileName: `${row.fileName}.${name}`,
      id: row.id,
    };
    updateAttachment(params).then(() => {
      const arr = [...details.supportEntities];
      const index = arr.findIndex((a) => a.id === row.id);
      arr[index].edit = false;
      arr[index].fileName = params.fileName;
      arr[index].rawFileName = row.cacheFileName;
      setViolationDetails((a) => ({ ...a, supportEntities: arr }));
    });
  };

  const onCancel = (row) => {
    const arr = [...details.supportEntities];
    const index = arr.findIndex((a) => a.id === row.id);

    arr[index].fileName = arr[index].cacheFileName;
    arr[index].edit = false;
    setViolationDetails((a) => ({ ...a, supportEntities: arr }));
  };

  const listItemEle = (a, edit = false) => {
    return (
      <>
        <IconFile className={cs(styles['item-icon'])} />
        <div className={cs(styles['item-text'])}>
          {a.edit && edit ? (
            <>
              <Input
                onPressEnter={(enevt) => {
                  enevt.stopPropagation();
                  onEnd(a);
                }}
                onChange={(e) => (a.fileName = e)}
                suffix={
                  <>
                    <IconCheck
                      onClick={(enevt) => {
                        enevt.stopPropagation();
                        onEnd(a);
                      }}
                      className={styles['item-icon-hover']}
                    />
                    <IconClose
                      onClick={(enevt) => {
                        enevt.stopPropagation();
                        onCancel(a);
                      }}
                      className={styles['item-icon-hover']}
                    />
                  </>
                }
              ></Input>
            </>
          ) : (
            <div
              title={`${a.fileName ? a.fileName : a.href}${
                a.rawFileName ? '(' + a.rawFileName + ')' : ''
              }`}
              className={cs(styles['item-span'], 'ellipsis', rtl ? 'ltr' : '')}
            >
              {a.fileName ? a.fileName : a.href}
              {a.rawFileName && `(${a.rawFileName})`}
            </div>
          )}
        </div>
        <div>
          {a.isDel ? (
            <IconDelete
              className={styles['item-icon-hover']}
              onClick={(enevt) => {
                enevt.stopPropagation();
                onRemove(a.href);
              }}
            />
          ) : (
            !a.edit && (
              <IconEdit
                className={styles['item-icon-hover']}
                onClick={(enevt) => {
                  enevt.stopPropagation();
                  onStart(a);
                }}
              />
            )
          )}

          <ActionWrapper action="violation.detail.file/link">
            <IconToBottom className={styles['item-icon-hover']} />
          </ActionWrapper>
        </div>
      </>
    );
  };

  return (
    <Spin tip={t['upload.loading']} style={{ width: '100%' }}>
      <div className={cs(styles['block'], styles['upload'], rtl ? 'rtl' : '')}>
        <div className={styles['block-title']}>
          {t['attachments.attachments']}
        </div>
        <Skeleton loading={loading} text={{ width: '100%' }} animation>
          <div className={cs(styles['attachments'])}>
            <div className={cs(styles['question'])}>
              {t['attachments.website.question']}
              <span className={styles['other']}>
                (
                {details.supportEntities.filter(
                  (a) =>
                    a.bizType === 'VIOLATION_WEBSITE' ||
                    a.bizType === 'VIOLATION_ENTITY'
                ).length > 0
                  ? t['YES']
                  : t['NO']}
                )
              </span>
            </div>
            <div className={styles['list']}>
              {details.supportEntities
                .filter(
                  (a) =>
                    a.bizType === 'VIOLATION_WEBSITE' ||
                    a.bizType === 'VIOLATION_ENTITY'
                )
                .map((a, k) => (
                  <div
                    key={k}
                    className={cs(styles['item'], 'cursor-pointer')}
                    onClick={() => {
                      if (
                        actions.includes('violation.detail.file/link') &&
                        !a.edit
                      ) {
                        usedownloadDoc(a.href, a.fileName);
                      }
                      // showDoc(a.href);
                    }}
                  >
                    {listItemEle(a, true)}
                  </div>
                ))}
            </div>
          </div>
          <ActionWrapper action="violation.detail.addattachments">
            <Space size="large">
              <AppUpload
                onFile={onAdd}
                refNumber={details.refNumber}
                fileNum={details.supportEntities.length}
              >
                <Button type="primary" icon={<IconUpload />}>
                  {t['attachments.upload']}
                </Button>
              </AppUpload>
            </Space>
          </ActionWrapper>
          <div className={styles['list']}>
            {details.supportEntities
              .filter((a) => a.bizType === 'VIOLATION_SUPPORT')
              .map((a, k) => (
                <div
                  key={k}
                  className={cs(styles['item'], 'cursor-pointer')}
                  onClick={() => {
                    if (
                      actions.includes('violation.detail.file/link') &&
                      !a.edit
                    ) {
                      usedownloadDoc(a.href, a.fileName);
                    }
                    // showDoc(a.href);
                  }}
                >
                  {listItemEle(a, true)}
                </div>
              ))}
            {/* 新上传文件 */}
            {fileList.map((a, k) => (
              <div
                key={k}
                className={cs(styles['item'], 'cursor-pointer')}
                onClick={() => {
                  if (actions.includes('violation.detail.file/link')) {
                    usedownloadDoc(a.href, a.fileName);
                  }
                  // showDoc(a.href);
                }}
              >
                {listItemEle(a, true)}
              </div>
            ))}
          </div>
        </Skeleton>
      </div>
    </Spin>
  );
}

export default Attachments;
